package com.hanbang.gycatering.comeon;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hanbang.gangyu.R;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.RepairBeanData;
import com.hanbang.gycatering.homepage.BaseActivity;
import com.hanbang.gycatering.myviews.MyDialog;
import com.hanbang.gycatering.myviews.MyDialog.MODE;
import com.hanbang.gycatering.myviews.MyDialog.OnClickCallback;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.MyToast;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends BaseActivity {
	private EditText username, userphone, codetext, password1, password2,homenumber;
	private CheckBox checkBox;
	private TextView title,addressText;
	private int plotId = -1;
	private LinearLayout useraddress;
	private TextView authCodeButton = null;
	private ArrayList<Object> addressDatas = new ArrayList<Object>();
	// 验证码按钮倒计时 总时长和间隔时长
	private long totalTime = 60000, intervalTime = 1000;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		initView();
		setTheClick();
		getAddressData();
	}

	private void getAddressData() {
		// TODO Auto-generated method stub
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET, HttpInterfaces.getplot,
				new MyRequestCallBack<String>(RegisterActivity.this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							if (json.getInt("state") == 1) {
								JSONArray plot = json.getJSONObject("info").getJSONArray("plot");
								for (int i = 0; i < plot.length(); i++) {
									RepairBeanData repair = new RepairBeanData();
									repair.setId(plot.getJSONObject(i).getInt(
											"id"));
									repair.setName(plot.getJSONObject(i)
											.getString("name"));
									addressDatas.add(repair);
								}

							} else {
								MyToast.show(RegisterActivity.this, "获取数据失败",
										Toast.LENGTH_SHORT);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(RegisterActivity.this, "获取数据失败",
									Toast.LENGTH_SHORT);
						}
					}
				});
	}

	private void setTheClick() {
		// TODO Auto-generated method stub
		ImageView iv = (ImageView) findViewById(R.id.top_bar_left_image);
		iv.setVisibility(View.VISIBLE);
		iv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		// 验证码事件
		authCodeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				String phone = userphone.getText().toString().trim();
				title.setVisibility(View.VISIBLE);
				if (phone.equals("")) {
					title.setText("请输入手机号！");
					return;
				} else if (!phone.matches("^[1][3,5,7,8]+\\d{9}")) {
					title.setText("请输入正确的手机号！");
					return;
				}
				title.setVisibility(View.INVISIBLE);
				 getCode(phone,1);
			}
		});
		// 地址事件
		useraddress.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				MyDialog dialog = new MyDialog(RegisterActivity.this,
						R.style.about_me_dialog, MODE.SELECT){
						};
				dialog.setTitle("请选择您所在小区");
				dialog.setOnClickCallback(new OnClickCallback() {
					@Override
					public void onClick(MyDialog dialog, Object number,
							Object content) {
						if("-1".equals(String.valueOf(number))){
							addressText.setText(String.valueOf("请选择您所在小区"));
						}else{
							addressText.setText(((RepairBeanData) addressDatas
									.get((Integer) number)).getName());
							plotId = ((RepairBeanData) addressDatas
									.get((Integer) number)).getId();
						}
						
					}
				});
				dialog.setSelectData(addressDatas);
				dialog.show();
			}
		});
		// 注册协议事件
		findViewById(R.id.user_register_treaty).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(RegisterActivity.this,
								DealActivity.class);
						startActivity(intent);
					}
				});
		// 注册事件
		findViewById(R.id.user_register_button).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View view) {
						if (checkBox.isChecked()) {
							String t1 = username.getText().toString().trim();
							String t2 = userphone.getText().toString().trim();
							String t3 = password1.getText().toString().trim();
							String t4 = password2.getText().toString().trim();
							String t5 = codetext.getText().toString().trim();
							String t6 = homenumber.getText().toString().trim();
							title.setVisibility(View.VISIBLE);
							title.setText("");
							if (t1.equals("")) {
								title.setText("请输入昵称！");
								return;
							} else if (t2.equals("")) {
								title.setText("请输入手机号！");
								return;
							} else if (!t2.matches("^[1][3,5,7,8]+\\d{9}")) {
								title.setText("请输入正确的手机号！");
								return;
							}
							else if(plotId ==-1){
								title.setText("请选择您所在的小区");
								return;
							}
							 else if (t5 == null || t5.equals("")
							 || t5.length() != 6) {
							 title.setText("请输入6位数验证码！");
							 return;
							 }
							else if (t6.equals("")) {
								title.setText("请输入门牌号！");
								return;
							}
							else if (t3.equals("") || t4.equals("")) {
								title.setText("请输入密码！");
								return;
							}
							else if (t3.length() < 6 || t4.length() < 6) {
								title.setText("密码长度不足6位");
								return;
							} else if (!t3.equals(t4)) {
								title.setText("两次输入的密码不一致！");
								return;
							}
							title.setVisibility(View.INVISIBLE);
							postService(t1, t2, t3, t4,t5,plotId,t6);
						} else {
							title.setText("");
							Toast.makeText(RegisterActivity.this, "您未同意协议",
									Toast.LENGTH_SHORT).show();
						}
					}
				});

	}

	private void initView() {
		// TODO Auto-generated method stub
		((TextView) findViewById(R.id.top_bar_title)).setText("用户注册");
		title = (TextView) findViewById(R.id.user_register_title);
		// 发送验证码按钮
		authCodeButton = (TextView) findViewById(R.id.user_register_auth_code_button);
		addressText = (TextView) findViewById(R.id.user_text_address);
		username = (EditText) findViewById(R.id.user_register_name);
		userphone = ((EditText) findViewById(R.id.user_register_phone));
		codetext = (EditText) findViewById(R.id.user_register_auth_code_et);
		useraddress = (LinearLayout) findViewById(R.id.user_register_address);
		homenumber = (EditText) findViewById(R.id.user_register_homenumber);
		password1 = ((EditText) findViewById(R.id.user_register_password1));
		password2 = ((EditText) findViewById(R.id.user_register_password2));
		checkBox = (CheckBox) findViewById(R.id.user_register_checkbox);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
//注册事件
	private void postService(final String username, final String userphone,
			final String password1, final String password2,final String code ,final int plotid,final String house ) {
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET, HttpInterfaces.registeruser + "&username="
						+ username + "&userphone=" + userphone + "&password="
						+ password1 + "&password2=" + password2+"&code="+code
						+ "&plotid="+plotid+"&house="+house,
				new MyRequestCallBack<String>(RegisterActivity.this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							if (json.getInt("state") == 1) {
								MyLog.e("postService",
										HttpInterfaces.registeruser
												+ "&username=" + username
												+ "&userphone=" + userphone
												+ "&password=" + password1
												+ "&password2=" + password2+"&code="+code
												+"&plotid="+plotId+"&house"+house);
								Intent intent = new Intent(
										RegisterActivity.this,
										LoginActivity.class);
								intent.putExtra("userphone", userphone);
								intent.putExtra("password", password1);
								setResult(999, intent);
								finish();
							} else {
								MyToast.show(RegisterActivity.this, "注册失败",
										Toast.LENGTH_SHORT);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(RegisterActivity.this, "注册失败",
									Toast.LENGTH_SHORT);
						}
					}
				});
	}
 
		 //获取验证码
		 private void getCode(String phone,int type) {
			 ((MyApplication) getApplicationContext()).httpUtils.send(
						HttpMethod.GET, HttpInterfaces.code + "&userphone="
								+ phone + "&type="+ type ,
						new MyRequestCallBack<String>(RegisterActivity.this,
								getString(R.string.loadding)) {
							@Override
							public void onSuccess(ResponseInfo<String> responseInfo) {
								super.onSuccess(responseInfo);
								try {
									JSONObject json = new JSONObject(
											responseInfo.result);
									if (json.getInt("state") == 1) {
										countDownTimer.start(); 
									} else {
										MyToast.show(RegisterActivity.this, json.getString("erro"),
												Toast.LENGTH_SHORT);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									MyToast.show(RegisterActivity.this, "注册失败",
											Toast.LENGTH_SHORT);
								}
							}
						});
		 
	}

	CountDownTimer countDownTimer = new CountDownTimer(totalTime, intervalTime) {
		@Override
		public void onFinish() {// 计时完毕时触发
			authCodeButton.setText("重新发送");
			authCodeButton.setEnabled(true);
			// authCodeButton.setClickable(true);
		}

		@Override
		public void onTick(long currentTime) {// 计时过程显示
			// authCodeButton.setClickable(false);
			authCodeButton.setEnabled(false);
			authCodeButton.setText(currentTime / 1000 + "秒");
		}
	};
}
